import React, { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Tag, Button, Space, message } from 'antd';
import { UserOutlined, DollarOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { request } from '@umijs/max';

const AssistReceivable = () => {
  const actionRef = useRef();
  const [summaryData, setSummaryData] = useState({
    totalCustomers: 0,
    totalReceivableAmount: 0,
  });

  // 列状态管理 - 控制哪些列默认隐藏
  const [columnsStateMap, setColumnsStateMap] = useState({
    salesperson: {
      show: false, // 接单人默认隐藏
    },
    lastPushTime: {
      show: false, // 上次推送时间默认隐藏
    },
    assistant: {
      show: false, // 协助人默认隐藏
    },
  });

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 计算合计数据
  const calculateSummary = (data) => {
    const totalCustomers = data.length;
    const totalReceivableAmount = data.reduce((sum, item) => {
      return sum + (item.receivableAmount || 0);
    }, 0);

    setSummaryData({
      totalCustomers,
      totalReceivableAmount,
    });
  };

  // 表格列配置
  const columns = [
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 150,
      fixed: 'left',
    },
    {
      title: '服务项目',
      dataIndex: 'serviceProject',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '客户编号',
      dataIndex: 'customerCode',
      width: 100,
      fixed: 'left',
    },
    {
      title: '客户评级',
      dataIndex: 'customerRating',
      width: 100,
      valueType: 'select',
      valueEnum: {
        'A+': { text: 'A+' },
        'A': { text: 'A' },
        'A-': { text: 'A-' },
        'B+': { text: 'B+' },
        'B': { text: 'B' },
        'C+': { text: 'C+' },
        'C': { text: 'C' },
      },
    },
    {
      title: '联系人',
      dataIndex: 'contactPerson',
      width: 100,
    },
    {
      title: '联系电话',
      dataIndex: 'contactPhone',
      width: 120,
    },
    {
      title: '收款月份',
      dataIndex: 'paymentMonth',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '2024-01': { text: '2024-01' },
        '2024-02': { text: '2024-02' },
        '2024-03': { text: '2024-03' },
        '2024-04': { text: '2024-04' },
        '2024-05': { text: '2024-05' },
        '2024-06': { text: '2024-06' },
      },
    },
    {
      title: '服务期间',
      dataIndex: 'servicePeriod',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '应收服务费',
      dataIndex: 'receivableAmount',
      width: 120,
      hideInSearch: true,
      render: (amount) => `¥${amount?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '收款备注',
      dataIndex: 'paymentRemark',
      width: 120,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '成员企业',
      dataIndex: 'memberEnterprise',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '是': { text: '是' },
        '否': { text: '否' },
      },
      render: (status) => (
        <Tag color={status === '是' ? 'success' : 'default'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '区域',
      dataIndex: 'area',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '北京': { text: '北京' },
        '上海': { text: '上海' },
        '深圳': { text: '深圳' },
        '广州': { text: '广州' },
        '杭州': { text: '杭州' },
        '成都': { text: '成都' },
        '武汉': { text: '武汉' },
        '南京': { text: '南京' },
      },
    },
    {
      title: '接单人',
      dataIndex: 'salesperson',
      width: 100,
    },
    {
      title: '记账会计',
      dataIndex: 'accountant',
      width: 100,
    },
    {
      title: '关注微信',
      dataIndex: 'followWechat',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '已关注': { text: '已关注' },
        '未关注': { text: '未关注' },
      },
      render: (status) => (
        <Tag color={status === '已关注' ? 'success' : 'warning'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '已收金额',
      dataIndex: 'receivedAmount',
      width: 120,
      hideInSearch: true,
      render: (amount) => `¥${amount?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '已收费至',
      dataIndex: 'receivedUpTo',
      width: 100,
      hideInSearch: true,
      render: (month) => month || '-',
    },
    {
      title: '收款状态',
      dataIndex: 'paymentStatus',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '已收齐': { text: '已收齐' },
        '部分收款': { text: '部分收款' },
        '未收款': { text: '未收款' },
      },
      render: (status) => {
        const color = status === '已收齐' ? 'success' : status === '部分收款' ? 'warning' : 'error';
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: '上次推送时间',
      dataIndex: 'lastPushTime',
      width: 160,
      hideInSearch: true,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '收款单',
      dataIndex: 'receiptNumber',
      width: 120,
      hideInSearch: true,
      render: (number) => number || '-',
    },
    {
      title: '协助人',
      dataIndex: 'assistant',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '协助原因',
      dataIndex: 'assistReason',
      width: 150,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '协助等级',
      dataIndex: 'assistLevel',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '高': { text: '高' },
        '中': { text: '中' },
        '低': { text: '低' },
      },
      render: (level) => {
        const color = level === '高' ? 'error' : level === '中' ? 'warning' : 'default';
        return <Tag color={color}>{level}</Tag>;
      },
    },
    {
      title: '协助状态',
      dataIndex: 'assistStatus',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '待处理': { text: '待处理' },
        '进行中': { text: '进行中' },
        '已解决': { text: '已解决' },
      },
      render: (status) => {
        const color = status === '已解决' ? 'success' : status === '进行中' ? 'processing' : 'default';
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 260,
      fixed: 'right',
      hideInSearch: true,
      render: (text, record) => (
        <Space>
          <Button size="small" onClick={() => handleCopy(record)}>复制账单</Button>
          <Button size="small" onClick={() => handleCollect(record)}>收款</Button>
          <Button size="small" onClick={() => handlePush(record)}>推送</Button>
          <Button size="small" onClick={() => handleAssist(record)}>协助</Button>
        </Space>
      ),
    },
  ];

  const handleCopy = (record) => {
    console.log(record);
    message.info(`复制账单 ( ${record.customerName} )`);
  };
  const handleCollect = (record) => {
    console.log(record);
    message.info(`收款 ( ${record.customerName} )`);
  };
  const handlePush = (record) => {  
    console.log(record);
    message.info(`推送 ( ${record.customerName} )`);
  };
  const handleAssist = (record) => {
    console.log(record);
    message.info(`协助 ( ${record.customerName} )`);
  };

  // 获取数据的函数
  const getContractPayments = async (params) => {
    try {
      const response = await request('/api/assist-receivables', {
        method: 'GET',
        params: {
          ...params,
          current: params.current || 1,
          pageSize: params.pageSize || 10,
        },
      });
      
      // 计算合计数据
      const data = response.data.list || [];
      calculateSummary(data);
      
      return {
        data: data,
        success: response.success,
        total: response.data.total,
      };
    } catch (error) {
      console.error('获取协助收款数据失败:', error);
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  return (
    <PageContainer
      header={{
        title: '协助收款',
        subTitle: '协助收款管理页面',
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={getContractPayments}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        toolBarRender={() => [
          <div key="summary" style={{
            display: 'flex',
            alignItems: 'center',
            gap: '24px',
            fontSize: '14px',
            color: '#666'
          }}>
            <span>
              <UserOutlined style={{ marginRight: '4px', color: '#1890ff' }} />
              合计：<strong style={{ color: '#1890ff' }}>{summaryData.totalCustomers}</strong> 户
            </span>
            <span>
              <DollarOutlined style={{ marginRight: '4px', color: '#52c41a' }} />
              待收费合计：<strong style={{ color: '#52c41a' }}>¥{summaryData.totalReceivableAmount.toLocaleString()}</strong> 元
            </span>
          </div>
        ]}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
          filterType: 'light',
          placement: 'bottomLeft',
        }}
        scroll={{ x: 2000 }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        dateFormatter="string"
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        tableAlertOptionRender={({selectedRowKeys, selectedRows}) => {
          return (
            <Button type="primary" size="small" onClick={() => {
              message.info(`批量推送 ( ${selectedRowKeys.length} )`);
            }}>
              批量推送 ( {selectedRowKeys.length} )
            </Button>
          );
        }}
      />
    </PageContainer>
  );
};

export default AssistReceivable; 